<?php

/**
 * Implements hook_theme().
 */
function weitheme_theme() {
  return array(
    'top_navbar' => array(
      'variables' => array('links' => array()),
    ),
    'bottom_navbar' => array(
      'variables' => array('links' => array()),
    ),
  );
}

/**
 * Implements hook_preprocess_html().
 */
function weitheme_preprocess_html(&$variables) {
  // Add variables for path to theme.
  $variables['base_path'] = base_path();

  // Add body classes if certain regions have content.
  if (!empty($variables['page']['featured'])) {
    $variables['classes_array'][] = 'featured';
  }

}

/**
 * Override or insert variables into the page template for HTML output.
 */
function weitheme_process_html(&$variables) {
}

/**
 * Override or insert variables into the page template.
 */
function weitheme_preprocess_page(&$variables) {

  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }

  $variables['app_classes'] = array('app');
  // Add top navbar
  $top_navbar_id = theme_get_setting('weitheme_top_navbar');
  if ($top_navbar_id) {
    $links = menu_tree($top_navbar_id);
    if(!empty($links)) {
      $variables['top_navbar'] = theme('top_navbar', array('links' => $links));
      $variables['app_classes'][] = 'has-navbar-top';
    }
  }
  // Add bottom navbar
  $bottom_navbar_id = theme_get_setting('weitheme_bottom_navbar');
  if ($bottom_navbar_id) {
    $links = menu_tree($bottom_navbar_id);
    if(!empty($links)) {
      $variables['bottom_navbar'] = theme('bottom_navbar', array('links' => $links));
      $variables['app_classes'][] = 'has-navbar-bottom';
    }
  }

  // $vid = 2;
  // $terms = taxonomy_get_tree($vid);
  // $links = array();
  // foreach ($terms as $term) {
  //   $links[$term->tid] = array(
  //     '#title' => $term->name,
  //     '#href' => 'feeds',
  //     '#localized_options' => array(
  //       'query' => array('channel' => $term->tid),
  //     ),
  //   );
  // }
  // $variables['top_navbar'] = theme('top_navbar', array('links' => $links));

  // Added list markups and classes to node list.
  $is_front = drupal_is_front_page();
  $is_taxonomy = arg(0) == 'taxonomy' && arg(1) == 'term';
  if ($is_front || $is_taxonomy) {
    if(isset($variables['page']['content']['system_main']['nodes'])) {
      $build = &$variables['page']['content']['system_main'];
      //    dvr($build);die;
      $build['nodes']['#prefix'] = '<ul class="list-group">';
      $build['nodes']['#suffix'] = '</ul>';
      foreach ($build['nodes'] as &$build_node) {
        $build_node['#prefix'] = '<li class="list-group-item">';
        $build_node['#suffix'] = '</li>';
      }
    }
  }
}

/**
 * Implements hook_process_page().
 */
function weitheme_process_page(&$variables) {
  $variables['app_classes'] = implode(' ', $variables['app_classes']);
}

/**
 * Implements hook_preprocess_maintenance_page().
 */
function weitheme_preprocess_maintenance_page(&$variables) {
  // By default, site_name is set to Drupal if no db connection is available
  // or during site installation. Setting site_name to an empty string makes
  // the site and update pages look cleaner.
  // @see template_preprocess_maintenance_page
  if (!$variables['db_is_active']) {
    $variables['site_name'] = '';
  }
  drupal_add_css(drupal_get_path('theme', 'responsive_bartik') . '/css/maintenance-page.css');
}

/**
 * Override or insert variables into the maintenance page template.
 */
function weitheme_process_maintenance_page(&$variables) {
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}

/**
 * Override or insert variables into the node template.
 */
function weitheme_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
  if ($variables['view_mode'] == 'teaser') {
    $variables['theme_hook_suggestions'][] = 'node__teaser';
    $variables['theme_hook_suggestions'][] = 'node__'. $variables['node']->type .'__teaser';
  }
}

/**
 * Override or insert variables into the block template.
 */
function weitheme_preprocess_block(&$variables) {
  // In the header region visually hide block titles.
  if ($variables['block']->region == 'header') {
    $variables['title_attributes_array']['class'][] = 'element-invisible';
  }
}

/**
 * Implements theme_menu_tree().
 */
function weitheme_menu_tree($variables) {
  return '<ul class="menu clearfix">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_field__field_type().
 */
function weitheme_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

/**
 * Implements theme_item_list().
 */
function weitheme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];

  // Only output the list container and title, if there are any list items.
  // Check to see whether the block title exists before adding a header.
  // Empty headers are not semantic and present accessibility challenges.
  
  // $output = '<div class="item-list">';
  $output = '';
  if (isset($title) && $title !== '') {
    $output .= '<h3>' . $title . '</h3>';
  }

  if (!empty($items)) {
    $output .= "<$type" . drupal_attributes($attributes) . '>';
    $num_items = count($items);
    $i = 0;
    foreach ($items as $item) {
      $attributes = array();
      $children = array();
      $data = '';
      $i++;
      if (is_array($item)) {
        foreach ($item as $key => $value) {
          if ($key == 'data') {
            $data = $value;
          }
          elseif ($key == 'children') {
            $children = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $data = $item;
      }
      if (count($children) > 0) {
        // Render nested list.
        $data .= theme_item_list(array('items' => $children, 'title' => NULL, 'type' => $type, 'attributes' => $attributes));
      }
      if ($i == 1) {
        $attributes['class'][] = 'first';
      }
      if ($i == $num_items) {
        $attributes['class'][] = 'last';
      }
      $output .= '<li' . drupal_attributes($attributes) . '>' . $data . "</li>\n";
    }
    $output .= "</$type>";
  }
  // $output .= '</div>';
  return $output;
}


/**
 * Implements theme_pager().
 */
function weitheme_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
        'class' => array('pager-first'),
        'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '<span>…</span>',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_previous', array('text' => $i, 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('pager-current'),
            'data' => "<span class='active'>$i</span>",
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_next', array('text' => $i, 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
        'class' => array('pager-last'),
        'data' => $li_last,
      );
    }
    return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}

/**
 * Implements theme_menu_local_action().
 */
function weitheme_menu_local_action($variables) {
  $link = $variables['element']['#link'];

  // $output = '<li>';
  if (isset($link['href'])) {
    $options = isset($link['localized_options']) ? $link['localized_options'] : array();
    $options['attributes']['class'] = array('btn', 'btn-default');
    $output = l($link['title'], $link['href'], $options);
  }
  elseif (!empty($link['localized_options']['html'])) {
    $output = $link['title'];
  }
  else {
    $output = check_plain($link['title']);
  }
  // $output .= "\n";

  return $output."\n";
}

/**
 * Implements theme_menu_local_task().
 */
function weitheme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
}

function weitheme_menu_local_tasks(&$variables) {
  $output = '';

  if (!empty($variables['primary'])) {
    // $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
    $variables['primary']['#prefix'] .= '<ul class="nav nav-tabs primary-tabs">';
    $variables['primary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['primary']);
  }
  if (!empty($variables['secondary'])) {
    // $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
    $variables['secondary']['#prefix'] .= '<ul class="nav nav-tabs secondary-tabs">';
    $variables['secondary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['secondary']);
  }

  return $output;
}

/**
 * Implements theme_top_navbar().
 */
function weitheme_top_navbar($variables) {
  $links = $variables['links'];

  $output = '';
  $output .= '<nav class="navbar navbar-app navbar-absolute-top" role="navigation">'."\n";
  $output .= '<div class="scrollable"><div class="nav nav-links scrollable-content">'."\n";
  foreach (element_children($links) as $i) {
    $options = isset($links[$i]['#localized_options']) ? $links[$i]['#localized_options'] : array();
    $options['attributes']['class'] = array('menu-item');
    $output .= l($links[$i]['#title'], $links[$i]['#href'], $options);
  }
  $output .= '</div></div>'."\n";
  $output .= '</nav>'."\n";

  return $output;
}

/**
 * Implements theme_bottom_navbar().
 */
function weitheme_bottom_navbar($variables) {
  $links = $variables['links'];

  $output = '<div class="navbar-app navbar-absolute-bottom">'. "\n";
  $output .= '<ul id="navbar-bottom" class="btn-group justified">'. "\n";
  foreach (element_children($links) as $i) {
    $options = isset($links[$i]['#localized_options']) ? $links[$i]['#localized_options'] : array();
    $options['attributes']['class'] = array('btn', 'btn-block');

    $has_children = count($links[$i]['#below']);

    if ($has_children) {
      // print_r($links[$i]['#below']);die;
      $links[$i]['#below']['#theme_wrappers'] = array('menu_tree__navbar_popup');
      $children = drupal_render($links[$i]['#below']);
      $output .= '<li class="has_children">'."\n";
      $output .= '<span class="btn icon-up"><i class="fa fa-lg fa-angle-up"></i></span>' . "\n";
      $output .= '<span title="" class="btn btn-block">'. $links[$i]['#title'] .'</span>';
      $output .= $children . "\n";
    }
    else {
      $output .= '<li>' ."\n";
      $output .= l($links[$i]['#title'], $links[$i]['#href'], $options)."\n";
    } 
    $output .= '</li>'."\n";
  }
  $output .= '</ul></div>'. "\n";

  $js = <<<EOF
  jQuery(function(){
    var navbarBottom = jQuery('.has_children');
    navbarBottom.bind('click', function(){
      jQuery('.nav-popup-menu', this).slideToggle(100);
    });
  });
EOF;
  drupal_add_js($js, array('type'=>'inline'));

  return $output;

}

function weitheme_menu_tree__navbar_popup($variables) {
  return '<ul class="nav-popup-menu">' . $variables['tree'] . '</ul>';
}
